package com.lagou.edu.util;

import net.sf.cglib.beans.BeanCopier;

import java.util.List;
import java.util.stream.Collectors;

public class ConvertUtil {

    public static <S, T> T Convert(S source, T target) {
        if (source == null || target == null) {
            return null;
        }
        BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(), false);
        T result = target;
        copier.copy(source, result, null);
        return result;
    }


    public static <S, T> T Convert(S source, Class<T> target) {
        try {
            return Convert(source, target.newInstance());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static <S, T> List<T> Convert(List<S> source, Class<T> target) {
        if (source == null) {
            return null;
        }
        return source.stream().map(item -> {
            T result = null;
            try {
                result = target.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            Convert(item, result);
            return result;
        }).collect(Collectors.toList());

    }


}
